package org.osflash.arp
{
	import mx.rpc.AbstractService;
	import flash.utils.Proxy;
	import flash.utils.flash_proxy; // namespace
	import flash.net.Responder;
	import flash.utils.describeType;

	dynamic public class AMF0Service extends Proxy
	{
		private var gatewayURI:String;
		private var serviceName:String;
		private var gateway:RemotingConnection;
		
		public function AMF0Service ( gatewayURI:String, serviceName:String, gateway:RemotingConnection )
		{
			// Create remoting connection if necessary
			if ( gateway != null )
			{
				this.gateway = gateway;
			}
			else
			{
				this.gateway = new RemotingConnection ( gatewayURI );
			}
			
			// Save the serviceName
			this.serviceName = serviceName;
		}
		
		// Invokes a server-side method
		//
		// TODO: Investigate why objects don't show up with correct
		// datatypes in ServiceCapture (they are being as plain Objects)
		// Is the apply() method somehow stripping them of their datatype?
		//
		public function invoke ( methodName:String, args:Array, responder:Responder ):void
		{
			trace ("AMF0Service.invoke() called");
			var methodArgs:Array = [methodName, responder];
			trace ("args.length = " + args.length);
			for ( var i:uint = 0; i < args.length; i++ )
			{
				trace (args[i]);
 				methodArgs.push ( args[i] );
				trace (methodArgs[methodArgs.length-1]);
			}
			gateway.call.apply ( gateway, methodArgs );
		}
		
		flash_proxy override function callProperty(name:*, ...args):* 
		{
			// gateway.call( "sample.getUsers", new Responder(onResult, onFault));
			
			trace ("AMF0Service proxy - " + name );

			var methodName:String = serviceName + "." + name;
			var pendingCall:AMF0PendingCall = new AMF0PendingCall( this, methodName, args );
			
			return pendingCall;
		}
	}
}